package com.jmpt.fangbohui.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jmpt.fangbohui.Constants;
import com.jmpt.fangbohui.MyApplication;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.bean.BannerBean;
import com.jmpt.fangbohui.bean.PromoteBean;
import com.jmpt.fangbohui.bean.RecommendBean;
import com.jmpt.fangbohui.helper.CommonHelper;
import com.jmpt.fangbohui.helper.HistoryHelper;
import com.jmpt.fangbohui.http.ApiRequest;
import com.jmpt.fangbohui.http.JsonHttpHandler;
import com.jmpt.fangbohui.ui.BrokerPersonNetStoreHomePageActivity;
import com.jmpt.fangbohui.ui.BrokersListActivity;
import com.jmpt.fangbohui.ui.BuyNewHouseListActivity;
import com.jmpt.fangbohui.ui.BuyOldHouseListActivity;
import com.jmpt.fangbohui.ui.HouseDetailActivity;
import com.jmpt.fangbohui.ui.RentHouseListActivity;
import com.jmpt.fangbohui.ui.SelectCityActivity;
import com.jmpt.fangbohui.ui.WebActivity;
import com.jmpt.fangbohui.ui.base.BaseHeadFragment;
import com.jmpt.fangbohui.ui.personalcenter.BrokerOrderActivity;
import com.jmpt.fangbohui.utils.AppUtils;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.FileUtils;
import com.jmpt.fangbohui.utils.SpUtils;
import com.loopj.android.http.RequestHandle;

public class MainHomeFragment extends BaseHeadFragment implements OnClickListener {

	private  boolean isTouchBanner = false;
	private View mRootView;
	private TextView tv_head_location;
	private ImageButton ibtn_head_search;
	private ImageButton ibtn_head_map;
	private ViewPager vp_home_banner;
	private TextView tv_banner_index;
	private TextView tv_banner_title;
	
	private ImageView iv_navbar_image11;
	private ImageView iv_navbar_image12;
	private ImageView iv_navbar_image13;
	private ImageView iv_navbar_image14;
	private ImageView iv_navbar_image21;
	private ImageView iv_navbar_image22;
	private ImageView iv_navbar_image23;
	private ImageView iv_navbar_image24;
	private LinearLayout lin_home_promote1;
	private TextView tv_promote_title1;
	private TextView tv_promote_desc1;
	private ImageView iv_promote_image1;
	private LinearLayout lin_home_promote2;
	private TextView tv_promote_title2;
	private TextView tv_promote_desc2;
	private ImageView iv_promote_image2;
	private LinearLayout lin_home_promote3;
	private TextView tv_promote_title3;
	private TextView tv_promote_desc3;
	private ImageView iv_promote_image3;
	private LinearLayout lin_recommends_content;
	private ViewStub vs_ocation_selete;
	//导航栏 图标
	private ArrayList<ImageView> mCategoryImageViews;
	private LinearLayout lin_navbar_item11;
	private LinearLayout lin_navbar_item12;
	private LinearLayout lin_navbar_item13;
	private LinearLayout lin_navbar_item14;
	private LinearLayout lin_navbar_item21;
	private LinearLayout lin_navbar_item22;
	private LinearLayout lin_navbar_item23;
	private LinearLayout lin_navbar_item24;
	private List<RecommendBean> mRecommends;

	private List<PromoteBean> mPromotes;
	public List<BannerBean>  mBanners;
	private CountDownTimer mCountDownTimer;
	private BannerPagerAdapter mBannerPagerAdapter;

	public MainHomeFragment() {
		// Required empty public constructor
	}

	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		DebugLog.i("MainHomeFragment  --->  onCreateView");
		//确保不会重复添加
		if (mRootView != null) {
			ViewGroup parent = (ViewGroup) mRootView.getParent();
			if (parent != null) {
				parent.removeView(mRootView);
			}
			//返回原有的布局对象  不往下走了
			return mRootView;
		}
		super.onCreateView(inflater, container, savedInstanceState);
		mRootView = inflater.inflate(R.layout.fragment_home, container, false);
		mRootView = setContentView(mRootView);
		//隐藏基类的标题
		hideHeadArea();
		assignViews(mRootView);
        initView();
        
        initData();
        
        showHistoryData();
		
		return mRootView;
	}
	
	/**
	 * 显示历史缓存数据
	 */
	private void showHistoryData() {
		try {
			mBanners = HistoryHelper.getHistoryBannersData();
			refreshBanner();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			mRecommends = HistoryHelper.getHistoryRecommendsData();
			refreshRecommends();
		} catch (Exception e) {
			e.printStackTrace();
			showRecommendsLoading();
		}
		try {
			mPromotes = HistoryHelper.getHistoryPromotesData();
			refreshPromotes();
		} catch (Exception e) {
			e.printStackTrace();
			showPromotesLoading();
		}
	}


	/**
	 * 初始化页面所有的数据
	 */
	private void initData() {
		// TODO 初始化页面所有的数据
		initBannerData();
		initPromoteData();
		initRecommendsData();
		
		initFilterData();
	}
	
	private void initFilterData() {
		if(TextUtils.isEmpty(FileUtils.readJsonCache(Constants.SharedPreferences.NEW_HOUSE_FILTER))
				|| TextUtils.isEmpty(FileUtils.readJsonCache(Constants.SharedPreferences.OLD_HOUSE_FILTER))
						|| TextUtils.isEmpty(FileUtils.readJsonCache(Constants.SharedPreferences.RENT_HOUSE_FILTER))
								|| TextUtils.isEmpty(FileUtils.readJsonCache(Constants.SharedPreferences.AGENT_LIST_FILTER))
				){
			Intent intent = new Intent(getActivity(), SelectCityActivity.class);
			startActivity(intent);
		}
	}


	/**
	 * 初始化推荐数据
	 */
	private void initRecommendsData() {
		// TODO 初始化推荐数据
		RequestHandle requestHandle = ApiRequest.getRecommendsData(getActivity(), new HttpHomeRecommendsHandler(getActivity()));
        addRequestHandle(requestHandle);
	}


	/**
	 * 初始化促销商品数据
	 */
	private void initPromoteData() {
		// TODO 初始化促销商品数据
		RequestHandle requestHandle = ApiRequest.getPromotesData(getActivity(), new HttpHomePromotesHandler(getActivity()));
        addRequestHandle(requestHandle);
	}


	/**
	 * 初始化广告数据
	 */
	private void initBannerData() {
		// TODO Auto-generated method stub
		RequestHandle requestHandle = ApiRequest.getBannerData(getActivity(), new HttpHomeBannerHandler(getActivity()));
        addRequestHandle(requestHandle);
	}


	//查找界面控件
	private void assignViews(View view) {
		tv_head_location = (TextView) view.findViewById(R.id.tv_home_head_location);
		ibtn_head_search = (ImageButton) view.findViewById(R.id.ibtn_home_head_search);
		ibtn_head_map = (ImageButton) view.findViewById(R.id.ibtn_home_head_map);
		vp_home_banner = (ViewPager) view.findViewById(R.id.vp_home_banner);
		tv_banner_index = (TextView) view.findViewById(R.id.tv_home_banner_index);
		tv_banner_title = (TextView) view.findViewById(R.id.tv_home_banner_title);
		
		lin_navbar_item11 = (LinearLayout) view.findViewById(R.id.lin_home_navbar_item11);
		lin_navbar_item12 = (LinearLayout) view.findViewById(R.id.lin_home_navbar_item12);
		lin_navbar_item13 = (LinearLayout) view.findViewById(R.id.lin_home_navbar_item13);
		//lin_navbar_item14 = (LinearLayout) view.findViewById(R.id.lin_home_navbar_item14);
		lin_navbar_item21 = (LinearLayout) view.findViewById(R.id.lin_home_navbar_item21);
		lin_navbar_item22 = (LinearLayout) view.findViewById(R.id.lin_home_navbar_item22);
		lin_navbar_item23 = (LinearLayout) view.findViewById(R.id.lin_home_navbar_item23);
		//lin_navbar_item24 = (LinearLayout) view.findViewById(R.id.lin_home_navbar_item24);
		
		iv_navbar_image11 = (ImageView) lin_navbar_item11.findViewById(R.id.iv_home_navbar_image11);
		iv_navbar_image12 = (ImageView) lin_navbar_item12.findViewById(R.id.iv_home_navbar_image12);
		iv_navbar_image13 = (ImageView) lin_navbar_item13.findViewById(R.id.iv_home_navbar_image13);
		//iv_navbar_image14 = (ImageView) lin_navbar_item14.findViewById(R.id.iv_home_navbar_image14);
		iv_navbar_image21 = (ImageView) lin_navbar_item21.findViewById(R.id.iv_home_navbar_image21);
		iv_navbar_image22 = (ImageView) lin_navbar_item22.findViewById(R.id.iv_home_navbar_image22);
		iv_navbar_image23 = (ImageView) lin_navbar_item23.findViewById(R.id.iv_home_navbar_image23);
		//iv_navbar_image24 = (ImageView) lin_navbar_item24.findViewById(R.id.iv_home_navbar_image24);
		
		//lin_home_promote1 = (LinearLayout) view.findViewById(R.id.lin_home_promote1);
		//tv_promote_title1 = (TextView) view.findViewById(R.id.tv_home_promote_title1);
		//tv_promote_desc1 = (TextView) view.findViewById(R.id.tv_home_promote_desc1);
		//iv_promote_image1 = (ImageView) view.findViewById(R.id.iv_home_promote_image1);
		
	//	//lin_home_promote2 = (LinearLayout) view.findViewById(R.id.lin_home_promote2);
		//tv_promote_title2 = (TextView) view.findViewById(R.id.tv_home_promote_title2);
		//tv_promote_desc2 = (TextView) view.findViewById(R.id.tv_home_promote_desc2);
		//iv_promote_image2 = (ImageView) view.findViewById(R.id.iv_home_promote_image2);
		
		//lin_home_promote3 = (LinearLayout) view.findViewById(R.id.lin_home_promote3);
		//tv_promote_title3 = (TextView) view.findViewById(R.id.tv_home_promote_title3);
		//tv_promote_desc3 = (TextView) view.findViewById(R.id.tv_home_promote_desc3);
		//iv_promote_image3 = (ImageView) view.findViewById(R.id.iv_home_promote_image3);
		
		lin_recommends_content = (LinearLayout) view.findViewById(R.id.lin_home_recommends_content);
		
		vs_ocation_selete = (ViewStub) view.findViewById(R.id.vs_home_location_seleteStub);
		
	}
	/**
	 * 初始化控件
	 */
	private void initView() {
		// TODO 初始化控件
		tv_head_location.setOnClickListener(this);
		ibtn_head_search.setOnClickListener(this);
		ibtn_head_map.setOnClickListener(this);
		lin_navbar_item11.setOnClickListener(this);
		lin_navbar_item12.setOnClickListener(this);
		lin_navbar_item13.setOnClickListener(this);
		//lin_navbar_item14.setOnClickListener(this);
		lin_navbar_item21.setOnClickListener(this);
		lin_navbar_item22.setOnClickListener(this);
		lin_navbar_item23.setOnClickListener(this);
		//lin_navbar_item24.setOnClickListener(this);
		//把导航栏的图标放到集合了  待动态做屏幕适配
		mCategoryImageViews = new ArrayList<ImageView>();
		mCategoryImageViews.add(iv_navbar_image11);
		mCategoryImageViews.add(iv_navbar_image12);
		mCategoryImageViews.add(iv_navbar_image13);
		//mCategoryImageViews.add(iv_navbar_image14);
		mCategoryImageViews.add(iv_navbar_image21);
		mCategoryImageViews.add(iv_navbar_image22);
		mCategoryImageViews.add(iv_navbar_image23);
		//mCategoryImageViews.add(iv_navbar_image24);
		
		//适配分类图标大小
        DisplayMetrics metrics = AppUtils.getDispalyMetrics(getActivity());
        int categoryImageViewWidth = (int) (metrics.widthPixels / 4 * 0.5);
        for (int i = 0; i < mCategoryImageViews.size(); i++) {
            ViewGroup.LayoutParams layoutParams = mCategoryImageViews.get(i).getLayoutParams();
            layoutParams.width = categoryImageViewWidth;
            layoutParams.height = categoryImageViewWidth;
            mCategoryImageViews.get(i).setLayoutParams(layoutParams);
        }
        //适配顶部轮动广告高度
        ViewGroup.LayoutParams layoutParams = vp_home_banner.getLayoutParams();
        layoutParams.height = (int) (metrics.widthPixels * 0.5);
        vp_home_banner.setLayoutParams(layoutParams);
        //设置适配器
        mBannerPagerAdapter = new BannerPagerAdapter(getChildFragmentManager());
        vp_home_banner.setAdapter(mBannerPagerAdapter);
        
        vp_home_banner.setOnTouchListener(new View.OnTouchListener() {
            float oldX = 0;
            float newX = 0;
            float sens = 5;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        oldX = event.getX();
                        isTouchBanner = true;
                        break;

                    case MotionEvent.ACTION_UP:
                        newX = event.getX();
                        if (Math.abs(oldX - newX) < sens) {
                        	BannerBean bannerBean = mBanners.get(vp_home_banner.getCurrentItem());
                        	
                        	if(!TextUtils.isEmpty(bannerBean.getURL())){
                        		 Intent intent = new Intent(getActivity(), WebActivity.class);
                        		 intent.putExtra(WebActivity.URI_KEY, bannerBean.getURL());
                        		 startActivity(intent);
                        	}
//                        	int houseId = mBanners.get(vp_home_banner.getCurrentItem()).getHouse_id();
//                            int promoteId = mBanners.get(vp_home_banner.getCurrentItem()).getPromote_id();
//                            if (houseId > 0) {
//                                Intent intent = new Intent(getActivity(), HouseDetailActivity.class);
//                                intent.putExtra(HouseDetailActivity.EXTRAS_HOUSE_ID, houseId);
//                                startActivity(intent);
//                            } else if (promoteId > 0) {
//                                Intent intent = new Intent(getActivity(), PromoteDetailActivity.class);
//                                intent.putExtra(PromoteDetailActivity.EXTRAS_PROMOTE_ID, promoteId);
//                                startActivity(intent);
//                            }

                        }
                        oldX = 0;
                        newX = 0;
                        isTouchBanner = false;
                        break;
                }

                return false;
            }
        });
        
        vp_home_banner.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				refreshBannerInfo(position);
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// 屏蔽对外部滑动触摸的影响
				vp_home_banner.getParent().requestDisallowInterceptTouchEvent(true);
				vp_home_banner.getParent().getParent().requestDisallowInterceptTouchEvent(true);
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
			}
		});
        //控制广告轮动
        mCountDownTimer = new CountDownTimer(300000000, 5000) {
            @Override
            public void onTick(long l) {
                if (isTouchBanner == false) {
                    sliedToNextBanner();
                }
            }
            @Override
            public void onFinish() {

            }
        }.start();
        
		
	}

	/**
	 * 显示下一个轮动广告
	 */
	protected void sliedToNextBanner() {
		DebugLog.i("sliedToNextBanner...");
		try {
            if (mBannerPagerAdapter == null) {
                return;
            }
            int next = vp_home_banner.getCurrentItem() + 1;
            if (next == mBannerPagerAdapter.getCount()) {
                next = 0;
            }
            vp_home_banner.setCurrentItem(next,true);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}


	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.tv_home_head_location:
			intent = new Intent(getActivity(), SelectCityActivity.class);
			startActivity(intent);
			break;
		case R.id.lin_home_navbar_item11:  //新房
			if(TextUtils.isEmpty(FileUtils.readJsonCache(Constants.SharedPreferences.NEW_HOUSE_FILTER))){
				intent = new Intent(getActivity(), SelectCityActivity.class);
			}else{
				intent = new Intent(getActivity(), BuyNewHouseListActivity.class);
			}
			startActivity(intent);
			break;
		case R.id.lin_home_navbar_item12:  //二手房
			if(TextUtils.isEmpty(FileUtils.readJsonCache(Constants.SharedPreferences.OLD_HOUSE_FILTER))){
				intent = new Intent(getActivity(), SelectCityActivity.class);
			}else{
				intent = new Intent(getActivity(), BuyOldHouseListActivity.class);
			}
			startActivity(intent);
			break;
		case R.id.lin_home_navbar_item13:  //租房
			if(TextUtils.isEmpty(FileUtils.readJsonCache(Constants.SharedPreferences.RENT_HOUSE_FILTER))){
				intent = new Intent(getActivity(), SelectCityActivity.class);
			}else{
				intent = new Intent(getActivity(), RentHouseListActivity.class);
			}
			startActivity(intent);
			break;
		//case R.id.lin_home_navbar_item14: //名盘
			
		//	break;
		case R.id.lin_home_navbar_item22: //卖房
		case R.id.lin_home_navbar_item23: //出租
		case R.id.lin_home_navbar_item21: //中介联盟
			if(TextUtils.isEmpty(FileUtils.readJsonCache(Constants.SharedPreferences.AGENT_LIST_FILTER))){
				intent = new Intent(getActivity(), SelectCityActivity.class);
			}else{
				intent = new Intent(getActivity(), BrokersListActivity.class);
			}
			startActivity(intent);
			break;
	//	case R.id.lin_home_navbar_item24: //更多
			
		//	break;

		default:
			break;
		}
		
	}
	
	class HttpHomeRecommendsHandler extends JsonHttpHandler {
		
		public HttpHomeRecommendsHandler(Context context) {
			super(context);
		}
		
		@Override
		public void onDo(JSONArray response) {
			super.onDo(response);
			mRecommends = new Gson().fromJson(response.toString(),new TypeToken<List<RecommendBean>>() {}.getType());
			refreshRecommends();
			hideRecommendsLoading();
			//把数据保存到配置文件中
			MyApplication.getSharedPreferences().edit().putString(Constants.SharedPreferences.HOME_RECOMMENDS_DATA, new Gson().toJson(mRecommends)).commit();
		}
		
		@Override
		public void onStart() {
			super.onStart();
			showRecommendsLoading();
		}
		
		@Override
		public void onFinish() {
			super.onFinish();
		}
	}
	
	class HttpHomePromotesHandler extends JsonHttpHandler {
		

		public HttpHomePromotesHandler(Context context) {
			super(context);
		}
		
		@Override
		public void onDo(JSONArray response) {
			super.onDo(response);
			mPromotes = new Gson().fromJson(response.toString(),new TypeToken<List<PromoteBean>>() {}.getType());
			refreshPromotes();
			hidePromotesLoading();
			//把数据保存到配置文件中
			MyApplication.getSharedPreferences().edit().putString(Constants.SharedPreferences.HOME_PROMOTES_DATA, new Gson().toJson(mPromotes)).commit();
		}
		
		@Override
		public void onStart() {
			super.onStart();
			showPromotesLoading();
		}
		
		@Override
		public void onFinish() {
			super.onFinish();
		}
	}
	
	class HttpHomeBannerHandler extends JsonHttpHandler {

		public HttpHomeBannerHandler(Context context) {
			super(context);
		}

        @Override
        public void onDo(JSONArray response) {
        	mBanners = new Gson().fromJson(response.toString(),new TypeToken<List<BannerBean>>() {}.getType());
            refreshBanner();
        }
        
        @Override
        public void onCacheDo(JSONArray cache) {
        	DebugLog.d("onCacheDo : " + cache);
        	mBanners = new Gson().fromJson(cache.toString(),new TypeToken<List<BannerBean>>() {}.getType());
            refreshBanner();
        }

        @Override
        public void onStart() {
            super.onStart();
        }

        @Override
        public void onFinish() {
            super.onFinish();
        }
    }
	
	/**
	 * 刷新推荐信息
	 */
	public void refreshRecommends() {
		if(mRecommends == null) return;
		// TODO 刷新推荐信息
        for (int i = 0; i < mRecommends.size(); i++) {
            lin_recommends_content.addView(CommonHelper.getHomeRecommendsView(getActivity(), mRecommends.get(i), i));
        }
	}
	
	public void refreshBanner() {
		if(mBanners != null){
			mBannerPagerAdapter.notifyDataSetChanged();
			vp_home_banner.setCurrentItem(0);
			refreshBannerInfo(0);
		}
	}
	
	public void refreshBannerInfo(int position) {
		tv_banner_index.setText(position + 1 + "/" + mBanners.size());
		tv_banner_title.setText(mBanners.get(position).getADName());
	}

	public void showPromotesLoading() {
		// TODO Auto-generated method stub
		
	}


	public void hidePromotesLoading() {
		// TODO Auto-generated method stub
		
	}


	public void refreshPromotes() {
		if(mPromotes == null) return;
		// TODO Auto-generated method stub
		
	}


	/**
	 * 显示推荐信息加载动画
	 */
	public void showRecommendsLoading() {
		// TODO 显示推荐信息加载动画
		
	}

	/**
	 * 隐藏推荐信息加载动画
	 */
	public void hideRecommendsLoading() {
		// TODO 隐藏推荐信息加载动画
		
	}
	
	class BannerPagerAdapter extends FragmentStatePagerAdapter {

        public BannerPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
        public Fragment getItem(int position) {
            return HomeBannerFragment.create(mBanners.get(position).getSmallPic());
        }

        @Override
        public int getCount() {
            if (mBanners == null) {
                return 0;
            }
            return mBanners.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }
    }

}
